package com.example.stresstest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author zoRRo
 * @date 2020/11/7
 **/
@RestController
@Slf4j
public class TestRest {
    
    @Autowired
    HttpService httpService;
    
    @GetMapping("/test")
    public String doTest(@RequestParam(value = "url", defaultValue = "https://www.baidu.com") String url) throws ExecutionException, InterruptedException {
        
        List<Long> list = new ArrayList<>();
        
        long startTime = System.currentTimeMillis();
        
        int i = 0;
        while (i < 100) {
            Future<Long> futureResult = httpService.doGet(url);
            list.add(futureResult.get());
            i++;
        }
        
        long endTime = System.currentTimeMillis();
        log.info("总执行时长：" + (endTime - startTime) + "ms");
        
        Collections.sort(list);
        
        // 平均响应时间
        double avg = list.stream().mapToDouble(Number::doubleValue).average().getAsDouble();
        log.info("平均响应时间：" + avg + "ms");
        
        // 95% 响应时间
        log.info("95% 响应时间：" + list.get(95) + "ms");
        
        // 吞吐量
        double tps = 1000 / avg * 10;
        log.info("吞吐量：" + tps);
        
        return "平均响应时间：" + avg + "ms;" + "95% 响应时间：" + list.get(95) + "ms";
    }
    
}
